import React, {
  FC,
  ReactElement,
  useState,
  useEffect,
  useImperativeHandle,
  forwardRef,
} from 'react'
import { Upload, Button } from 'antd'
import {
  LoadingOutlined,
  PlusOutlined,
  InfoCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons'
import style from './index.less'
import { sendPictureUpload } from '@/services'
import commonStyle from '@/pages/publicStyle'

interface IProp {
  tagMessage?: string
  tagPosition?: Boolean
  isImgBtn?: Boolean
  UploadSuccess: () => void
}
const UploadCom = forwardRef((props: IProp, ref: any): ReactElement => {
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState('')
  const customRequestMy = (option: any) => {
    // console.log('上传', option);

    const formData = new FormData()
    formData.append('multipartFile', option.file)
    sendPictureUpload(formData, {}).then(res => {
      console.log(1111223, res)

      if (res?.code === 200) {
        if (props.isImgBtn) setImageUrl(res.data.imgUrl)
        props.UploadSuccess(res.data)
      }
    })
  }
  const initImgSrc = (imgUrl: string) => {
    setImageUrl(imgUrl)
  }
  useImperativeHandle(ref, () => {
    return {
      initImgSrc,
    }
  })
  useEffect(() => {}, [])
  const { avatarUploader, tagMessageFont } = style
  const { flexBox, ml10 } = commonStyle
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  )
  return (
    <div style={props.tagPosition ? flexBox : {}}>
      <Upload
        name="avatar"
        listType={props.isImgBtn ? 'picture-card' : 'text'}
        className={props.isImgBtn ? avatarUploader : ''}
        showUploadList={!props.isImgBtn}
        customRequest={customRequestMy}
        disabled={!!imageUrl}
      >
        {!props.isImgBtn ? (
          <Button icon={<UploadOutlined />}>Click to Upload</Button>
        ) : imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{ width: '100%', height: '100%' }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
      {props.tagMessage && (
        <div
          className={tagMessageFont}
          style={props.tagPosition ? { ...ml10, width: '60%' } : {}}
        >
          <InfoCircleOutlined
            style={{
              color: '#fc9c03',
              marginRight: '5px',
            }}
          />
          <span
            dangerouslySetInnerHTML={{ __html: `${props.tagMessage}` }}
          ></span>
        </div>
      )}
    </div>
  )
})
export default UploadCom
